<template>
  <div class="container">
    <header class="header">
      <div class="logo">MYblog</div>
      <nav class="nav">
        <div class="jump-buttons">
          <el-button v-if="isCreatorVisible" type="primary" @click="goCreator">进入创作者中心</el-button>
          <el-button v-if="isAdminVisible" type="success" @click="goAdmin">进入后台管理</el-button>
        </div>
        <span v-if="!isLoggedIn" class="login" @click="showLogin = true">登录</span>
        <span v-else class="login-account" @click="confirmLogout">账户：{{ userStore.userInfo.username }}</span>
        <LoginModal v-model="showLogin" @success="onLoginSuccess" />
      </nav>
    </header>

    <div class="search-bar">
      <input v-model.trim="searchQuery" placeholder="请输入搜索内容" @keyup.enter="search" />
      <button @click="search">🔍</button>
    </div>

    <div class="category-bar">
      <span
        v-for="item in categories"
        :key="item.id || item.name"
        :class="{ active: currentCategory.id === item.id }"
        @click="selectCategory(item)"
      >
        {{ item.name }}
      </span>
    </div>

    <div class="article-list">
      <ArticleCard v-for="article in articles" :key="article.id" :article="article" />
      <div v-if="articles.length === 0" style="text-align:center; color:#999; margin-top:20px;">
        没有找到相关文章~
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted,nextTick  } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

import ArticleCard from '@/components/ArticleCard.vue'
import LoginModal from '@/components/LoginModal.vue'
import * as tagApi from '@/api/tag'
import * as articleApi from '@/api/article'
import { useUserStore } from '@/stores/user'

interface CategoryItem {
  id: number | null
  name: string
}

const router = useRouter()
const userStore = useUserStore()

const showLogin = ref(false)
const searchQuery = ref('')
const articles = ref<any[]>([])
const categories = ref<CategoryItem[]>([{ id: null, name: '全部' }])
const currentCategory = ref<CategoryItem>({ id: null, name: '全部' })

const isLoggedIn = computed(() => !!userStore.token && !!userStore.userInfo.username)
const isCreatorVisible = computed(() => [1, 2].includes(userStore.userInfo.usertype))
const isAdminVisible = computed(() => userStore.userInfo.usertype === 1)

function onLoginSuccess() {
  showLogin.value = false
  ElMessage.success('登录成功')
  fetchArticles()
}

function confirmLogout() {
  ElMessageBox.confirm('确定要退出登录吗？', '退出登录', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      userStore.logout()
      ElMessage.success('已退出登录')
      fetchArticles()
    })
    .catch(() => {})
}

async function fetchTags() {
  try {
    const res = await tagApi.getAllTags()
    if (res.code === 0) {
      categories.value = [
        { id: null, name: '全部' },
        ...res.data.map((t: any) => ({ id: t.id, name: t.name }))
      ]
    } else {
      ElMessage.warning(res.message || '标签加载失败')
    }
  } catch {
    ElMessage.error('标签加载失败')
  }
}

async function fetchArticles() {
  try {
    const res = await articleApi.getAllArticles()
    if (res.code === 0) {
      articles.value = res.data
    } else {
      ElMessage.warning(res.message || '文章加载失败')
    }
  } catch {
    ElMessage.error('请求文章列表失败')
  }
}

async function fetchArticlesByTag(tagId: number) {
  try {
    const res = await articleApi.getArticlesByTag(tagId)
    if (res.code === 0 && Array.isArray(res.data)) {
  articles.value = res.data
} else if (res.code === 0 && res.data === null) {
  articles.value = []
} else {
  ElMessage.warning(res.message || '文章加载失败')
}
  } catch {
    ElMessage.error('获取标签文章失败')
  }
}

async function searchArticles(keyword: string) {
  try {
    if (!keyword.trim()) {
      fetchArticles()
      return
    }
    const res = await articleApi.searchArticlesByTitle(keyword.trim())
    if (res.code === 0) {
      articles.value = res.data ?? []
      currentCategory.value = { id: null, name: '' }
    } else {
      ElMessage.warning(res.message || '搜索失败')
    }
  } catch {
    ElMessage.error('搜索失败')
  }
}

function search() {
  if (!searchQuery.value.trim()) {
    fetchArticles()
  } else {
    searchArticles(searchQuery.value)
  }
}

function selectCategory(category: CategoryItem) {
  currentCategory.value = category
  searchQuery.value = '' // 清空搜索框

  // 等待下一个 DOM 更新周期，确保 input 组件被重置
  nextTick(() => {
    if (category.id === null) {
      fetchArticles()
    } else {
      fetchArticlesByTag(category.id)
    }
  })
}

function goCreator() {
  router.push('/creator')
}
function goAdmin() {
  router.push('/admin')
}

onMounted(() => {
  fetchTags()
  fetchArticles()
})
</script>

<style scoped>
.container {
  padding: 0 40px;
  font-family: sans-serif;
  background: #ffffff;
  color: #333;
  min-height: 100vh;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}
.logo {
  font-size: 24px;
  font-weight: bold;
}
.nav {
  display: flex;
  align-items: center;
}
.login {
  margin-left: 15px;
  color: #1890ff;
  cursor: pointer;
}
.login-account {
  margin-left: 15px;
  color: #1890ff;
  font-weight: 600;
  cursor: pointer;
}
.jump-buttons {
  display: flex;
  gap: 12px;
  margin-right: 24px;
}
.search-bar {
  margin: 30px 0;
  display: flex;
  justify-content: center;
}
.search-bar input {
  width: 400px;
  padding: 8px;
  border: 1px solid #ccc;
  border-right: none;
  border-radius: 4px 0 0 4px;
}
.search-bar button {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}
.category-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}
.category-bar span {
  padding: 6px 12px;
  cursor: pointer;
  color: #666;
  background: #f2f2f2;
  border-radius: 20px;
  user-select: none;
}
.category-bar .active {
  background: #1890ff;
  color: white;
}
.article-list {
  margin-top: 20px;
}
</style>
